﻿using DAL;
using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Linq.Expressions;

namespace DianShangHouTai.Models
{
    public class BaseService<T> where T : class, new()
    {
        /// <summary>
        /// 获取对象
        /// </summary>
        /// <param name="whereLambda">条件的Lambda表达式</param>
        /// <returns></returns>
        public static T GetModel(Expression<Func<T, bool>> whereLambda)
        {
            using (ShopContext db = new ShopContext())
            {
                return db.Set<T>().FirstOrDefault(whereLambda);
            }
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="whereLambda">条件的Lambda表达式</param>
        /// <returns></returns>
        public static List<T> GetList(Expression<Func<T, bool>> whereLambda)
        {
            using (ShopContext db = new ShopContext())
            {
                return db.Set<T>().Where(whereLambda).ToList();
            }
        }
        /// <summary>
        /// 向数据库中添加当前对象
        /// </summary>
        /// <param name="T">要添加的对象</param>
        /// <returns></returns>
        public static int Add(T obj)
        {
            try
            {
                using (ShopContext db = new ShopContext())
                {
                    db.Set<T>().Add(obj);
                    return db.SaveChanges();
                }

            }
            catch (Exception)
            {
                return -1;
            }
        }
        /// <summary>
        /// 从数据库中删除该对象
        /// </summary>
        /// <param name="T">要删除的对象</param>
        public static int Delete(T obj)
        {
            try
            {
                using (ShopContext db = new ShopContext())
                {
                    db.Set<T>().Remove(obj);
                    return db.SaveChanges();
                }
            }
            catch (Exception)
            {
                return -1;
            }
        }
        /// <summary>
        /// 从数据库中修改该对象
        /// </summary>
        /// <param name="T">要删除的对象</param>
        public static int Update(T obj)
        {
            try
            {
                using (DAL.ShopContext db = new ShopContext())
                {
                    db.Set<T>().AddOrUpdate(obj);
                    return db.SaveChanges();
                }
            }
            catch (Exception)
            {
                return -1;
            }
        }
    }
}